import { NextRequest, NextResponse } from 'next/server'
import axios from 'axios'

// Unsplash API配置
const UNSPLASH_ACCESS_KEY = 'YOUR_UNSPLASH_ACCESS_KEY' // 需要替换为实际的API密钥
const UNSPLASH_API_URL = 'https://api.unsplash.com'

/**
 * 从故事内容中提取关键词用于图片搜索
 * @param storyContent 故事内容
 * @param ageGroup 年龄组
 * @returns 搜索关键词数组
 */
function extractKeywords(storyContent: string, ageGroup: string): string[] {
  // 根据年龄组调整关键词
  const ageKeywords = {
    '3-5': ['cute', 'colorful', 'simple', 'friendly'],
    '6-8': ['fun', 'adventure', 'bright', 'playful'],
    '9-12': ['exciting', 'mysterious', 'vibrant', 'dynamic']
  }

  // 从故事内容中提取主题关键词
  const commonThemes = [
    'animal', 'forest', 'castle', 'princess', 'dragon', 'space', 'ocean',
    'mountain', 'river', 'tree', 'flower', 'sun', 'moon', 'star',
    'house', 'car', 'train', 'plane', 'boat', 'bike', 'ball',
    'book', 'school', 'park', 'garden', 'beach', 'snow', 'rain'
  ]

  const extractedKeywords: string[] = []
  
  // 检查故事内容中的主题词
  commonThemes.forEach(theme => {
    if (storyContent.toLowerCase().includes(theme)) {
      extractedKeywords.push(theme)
    }
  })

  // 添加年龄组相关关键词
  const ageSpecificKeywords = ageKeywords[ageGroup as keyof typeof ageKeywords] || []
  extractedKeywords.push(...ageSpecificKeywords)

  // 如果没有找到关键词，使用默认关键词
  if (extractedKeywords.length === 0) {
    extractedKeywords.push('children', 'story', 'illustration')
  }

  return extractedKeywords.slice(0, 3) // 限制关键词数量
}

/**
 * 从Unsplash搜索图片
 * @param query 搜索关键词
 * @param count 图片数量
 * @returns 图片数据数组
 */
async function searchUnsplashImages(query: string, count: number = 1) {
  try {
    const response = await axios.get(`${UNSPLASH_API_URL}/search/photos`, {
      params: {
        query,
        per_page: count,
        orientation: 'landscape', // 适合故事插图的横向图片
        content_filter: 'high' // 高质量内容
      },
      headers: {
        'Authorization': `Client-ID ${UNSPLASH_ACCESS_KEY}`
      }
    })

    return response.data.results.map((photo: any) => ({
      id: photo.id,
      url: photo.urls.regular,
      thumb: photo.urls.thumb,
      alt: photo.alt_description || query,
      photographer: photo.user.name,
      photographerUrl: photo.user.links.html,
      downloadUrl: photo.links.download_location
    }))
  } catch (error) {
    console.error('Unsplash API错误:', error)
    return []
  }
}

/**
 * 生成故事插图
 * @param storyContent 故事内容
 * @param ageGroup 年龄组
 * @param style 图片风格
 * @returns 图片数据
 */
async function generateStoryIllustration(storyContent: string, ageGroup: string, style: string = 'watercolor') {
  // 提取关键词
  const keywords = extractKeywords(storyContent, ageGroup)
  
  // 根据风格调整关键词
  const styleKeywords = {
    'watercolor': ['watercolor', 'artistic', 'soft'],
    'cartoon': ['cartoon', 'illustration', 'fun'],
    'realistic': ['realistic', 'detailed', 'natural']
  }

  const searchQuery = `${keywords.join(' ')} ${styleKeywords[style as keyof typeof styleKeywords]?.join(' ') || ''}`.trim()
  
  // 搜索图片
  const images = await searchUnsplashImages(searchQuery, 1)
  
  if (images.length > 0) {
    return {
      url: images[0].url,
      thumb: images[0].thumb,
      alt: images[0].alt,
      photographer: images[0].photographer,
      photographerUrl: images[0].photographerUrl,
      source: 'Unsplash',
      prompt: searchQuery
    }
  }

  // 如果搜索失败，返回默认图片
  return {
    url: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=600&fit=crop',
    thumb: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=300&fit=crop',
    alt: 'Default story illustration',
    photographer: 'Unsplash',
    photographerUrl: 'https://unsplash.com',
    source: 'Unsplash',
    prompt: searchQuery
  }
}

/**
 * 生成漫画面板图片
 * @param storyContent 故事内容
 * @param ageGroup 年龄组
 * @param panelCount 面板数量
 * @returns 图片数据数组
 */
async function generateComicPanels(storyContent: string, ageGroup: string, panelCount: number = 4) {
  const keywords = extractKeywords(storyContent, ageGroup)
  const searchQuery = `${keywords.join(' ')} cartoon illustration comic`
  
  const images = await searchUnsplashImages(searchQuery, panelCount)
  
  return images.map((image, index) => ({
    url: image.url,
    thumb: image.thumb,
    alt: image.alt,
    photographer: image.photographer,
    photographerUrl: image.photographerUrl,
    source: 'Unsplash',
    prompt: searchQuery,
    panelIndex: index + 1
  }))
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { storyContent, ageGroup, style, type, panelCount } = body

    if (!storyContent) {
      return NextResponse.json(
        { error: '故事内容不能为空' },
        { status: 400 }
      )
    }

    let result

    if (type === 'comic') {
      // 生成漫画面板
      result = await generateComicPanels(storyContent, ageGroup, panelCount || 4)
    } else {
      // 生成主插图
      result = await generateStoryIllustration(storyContent, ageGroup, style)
    }

    return NextResponse.json({
      success: true,
      data: result,
      source: 'Unsplash',
      message: '图片搜索成功'
    })

  } catch (error) {
    console.error('图片搜索API错误:', error)
    return NextResponse.json(
      { 
        error: '图片搜索失败',
        details: error instanceof Error ? error.message : '未知错误'
      },
      { status: 500 }
    )
  }
} 